package observable.subject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.socket.server.request.IRequest;
import observable.observer.IMessageHandler;

//观察者模式的subject，负责转发消息
public class MessageCenter {
	private static Map<Integer, List<IMessageHandler>> observers = new HashMap<Integer, List<IMessageHandler>>();
	//消息注册
	public void register(int command, IMessageHandler handler){
		List<IMessageHandler> handlerList = null;
		if((handlerList = observers.get(command)) != null){
			handlerList.add(handler);
		}else {
			handlerList = new ArrayList<IMessageHandler>();
			handlerList.add(handler);
			observers.put(command, handlerList);
		}
	}
	//消息转发
	public boolean distribute(int command, IRequest request) throws Exception{
		List<IMessageHandler> handlerList = null;
		if((handlerList = observers.get(command)) != null){
			for (IMessageHandler handler : handlerList) {
				handler.handle(command, request);
			}
			return true;
		}
		else {
			return false;
		}
	}
	
	// to be finished when needed
	public boolean remove(){
		return false;}
}
